//
//  LookingTestingViewController.swift
//  E-CycleForShop
//
//  Created by enghou on 17/3/14.
//  Copyright © 2017年 xyxorigation. All rights reserved.
//

import UIKit

class FinalTestingViewController: BaseViewController,handleShoper {
    
    var id : Int = -1
    
    var head : TestPhoneModelView = TestPhoneModelView.init(frame: CGRect.init(x: 0, y: 0, width: YXDeviceWidth, height: 198 * YXHeightScale))
    
    var selectedButton = 0
    
    var serial : CameraView?
    
    var phoneView : PhoneLabelView?
    
    var testing : AutoTestingView?
    
    var function : FunctionTestView?
    
    var baseInfos : Dictionary<String,String> = ["":""]
    
    var price : Int = 0 {
        didSet{
            let pric = NumberToString.intToFloatString(number: price, radix: 100)
            head.priceRange = pric
        }
    }
    
    var url : String = ""
    
    var finalParam : Dictionary<String,String> = [:]
    
    var goods_id : Int = -1
    
    let shopperLbl = UILabel.init()
    
    var model : PhoneInfoModel?
    
    var shopperModel : ShopperModelItem? {
        didSet{
            if shopperModel != nil {
                shopperLbl.text = shopperModel!.name
            } else {
                shopperLbl.text = ""
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "评估价格"
        self.naviHide = false
        self.defaultBackButton()
        if model != nil {
            configView(model: model!)
        }
    }

    func addExtraView(param : Dictionary<String,String>) -> Void {
        let titleArr = ["内屏显示","触屏","具体型号","保修时间","边框外壳","屏幕外观","维修史","其他问题"]
        let content = ["屏幕显示正常","屏幕显示正常","国行","1个月以上","边框无瑕疵","外观无瑕疵","无维修","无"]
        var dict : Dictionary<String,String> = [:]
        let arr : Array<Dictionary<String,String>> = []
        var idx = 0
        for item in titleArr {
            dict["title"] = item
            dict["content"] = content[idx]
            idx = idx + 1
        }
        let test = AutoTestingView.init(frame: CGRect.init(x: 0, y: testing!.bottom(), width: 730 * YXWidthScale, height: 400))
        test.loadContent(title: "", message: "基本信息", infos: arr)
    }
    
    func configView(model : PhoneInfoModel) -> Void {
        let scroll = UIScrollView.init(frame: CGRect.init(x: 0, y: 0, width: YXDeviceWidth, height: YXDeviceHeight - 140 * YXHeightScale))
        scroll.showsVerticalScrollIndicator = false
        scroll.backgroundColor = UIColor.colorWithHexString(hex: "ececec")
        self.view.addSubview(scroll)
        
        head.title = model.phone_model
        scroll.addSubview(head)//done
        
        let tray = UIView.init(frame: CGRect.init(x: 0, y: head.bottom() + 6 * YXHeightScale, width: YXDeviceWidth, height: 0))
        tray.backgroundColor = UIColor.colorWithHexString(hex: "f3f3f5")
        scroll.addSubview(tray)
        
//        let shopperTray = UIView.init()
//        shopperTray.backgroundColor = UIColor.white
//        shopperTray.frame = CGRect.init(x: 10 * YXWidthScale, y: 16 * YXHeightScale, width: YXDeviceWidth - 20 * YXWidthScale, height: 130 * YXHeightScale)
//        let imageView = UIImageView.init()
//        imageView.frame = CGRect.init(x: 40 * YXWidthScale, y: 26 * YXHeightScale, width: 88 * YXWidthScale, height: 88 * YXHeightScale)
//        imageView.image = UIImage.load(name: "head_assessment_office")
//        shopperTray.addSubview(imageView)
//        shopperLbl.font = UIFont.systemFont(ofSize: 36 * YXWidthScale)
//        shopperLbl.textColor = UIColor.black
//        let size = "与德隆".StringSize(font: shopperLbl.font)
//        shopperLbl.frame = CGRect.init(x: imageView.right() + 30 * YXWidthScale, y: 65 * YXHeightScale - size.height / 2, width: 100, height: size.height)
//        if goods_id != -1 {
//            if let mod = DataCacher.shared().shopper(id: String(goods_id)) {
//                shopperModel = mod
//            } else {
//                getShopper()
//            }
//        }else {
//            getShopper()
//        }
//        shopperTray.addSubview(shopperLbl)
//        let imageViewEnter = UIImageView.init()
//        imageViewEnter.image = UIImage.load(name: "icon_enter")
//        imageViewEnter.frame = CGRect.init(x: shopperTray.width() - 48 * YXWidthScale, y: 65 * YXHeightScale - 14 * YXHeightScale, width: 16 * YXWidthScale, height: 28 * YXHeightScale)
//        shopperTray.addSubview(imageViewEnter)
//        let labelAdd = UILabel.init()
//        labelAdd.font = UIFont.systemFont(ofSize: 28 * YXWidthScale)
//        labelAdd.textColor = UIColor.colorWithHexString(hex: "909090")
//        labelAdd.text = "添加修改"
//        let sizeAdd = labelAdd.text!.StringSize(font: labelAdd.font)
//        labelAdd.frame = CGRect.init(x: imageViewEnter.left() - 12 * YXWidthScale - sizeAdd.width, y: 65 * YXHeightScale - sizeAdd.height / 2, width: sizeAdd.width, height: sizeAdd.height)
//        tray.addSubview(labelAdd)
//        let button = UIButton.init(type: .system)
//        button.frame = shopperTray.bounds
//        button.setImage(UIImage.image(color: UIColor.clear, size: button.frame.size), for: .normal)
//        button.setImage(UIImage.image(color: UIColor.init(white: 0, alpha: 0.3), size: button.frame.size), for: .highlighted)
//        button.addTarget(self, action: #selector(addShopper), for: .touchUpInside)
//        shopperTray.addSubview(button)
//        tray.addSubview(shopperTray)
//        
        let back = UIView.init(frame: CGRect.init(x: 10 * YXWidthScale, y:tray.bottom() + 16 * YXHeightScale, width: 730 * YXWidthScale, height: 0))
        scroll.addSubview(back)
        
        testing = AutoTestingView.init(frame: CGRect.init(x: 0, y: 0, width: 730 * YXWidthScale, height: 400))
        //将model打包成array
        let arr = PhoneContentGenerator.array(model: model)
        testing!.loadContent(title: "检测报告", message: "基本信息", infos: arr)
        back.addSubview(testing!)//done
        back.frame = CGRect.init(x: 10 * YXWidthScale, y: tray.bottom() + 16 * YXHeightScale, width: 730 * YXWidthScale, height: testing!.height())
        back.backgroundColor = testing!.backgroundColor
        let back1 = UIView.init(frame: CGRect.init(x: 10 * YXWidthScale, y: back.bottom(), width: 730 * YXWidthScale, height: 0))
        function = FunctionTestView.init(frame: CGRect.init(x: 42 * YXWidthScale, y: 64 * YXHeightScale, width: 636 * YXWidthScale, height: 528 * YXHeightScale))
        function!.content = PhoneContentGenerator.flagArr(model: model)//done
        function!.configContent()
        back1.addSubview(function!)
        scroll.addSubview(back1)
        
        back1.frame = CGRect.init(x: 10 * YXWidthScale, y: back.bottom(), width: 730 * YXWidthScale, height: function!.height() + 128 * YXHeightScale + 30)
        back1.backgroundColor = back.backgroundColor
        
        let back2 = UIView.init(frame: CGRect.init(x: 10 * YXWidthScale, y: back1.bottom(), width: 730 * YXWidthScale, height: 0))
        scroll.addSubview(back2)
        /****************/
        let dit = InfosGetter.infos(source: finalParam)
        let target = [dit[2],dit[3],dit[4]]
        /**求出提供给test的信息*/
        
        let test = AutoTestingView.init(frame: CGRect.init(x: 0, y: 0, width: 730 * YXWidthScale, height: 400 * YXHeightScale))
        test.loadContent(title: "外观检测", message: "基本信息", infos: target)
        back2.addSubview(test)
        back2.frame = CGRect.init(x: 10 * YXWidthScale, y: back1.bottom(), width: 730 * YXWidthScale, height: test.bottom())
        
        let mask = UIView.init(frame: CGRect.init(x: 0, y: back1.top() - 10 * YXHeightScale, width: 20 * YXHeightScale, height: 20 * YXHeightScale))
        mask.backgroundColor = scroll.backgroundColor
        mask.layer.cornerRadius = 10 * YXHeightScale
        scroll.addSubview(mask)
        
        let mask1 = UIView.init(frame: CGRect.init(x: YXDeviceWidth - 20 * YXWidthScale, y: back1.top() - 10 * YXWidthScale, width: 20 * YXWidthScale, height: 20 * YXWidthScale))
        mask1.backgroundColor = scroll.backgroundColor
        mask1.layer.cornerRadius = 10 * YXWidthScale
        scroll.addSubview(mask1)
        
        
        scroll.contentSize = CGSize.init(width: 0, height: back2.bottom() + 64)
        
        let mask2 = UIView.init(frame: CGRect.init(x: 0, y: back1.bottom() - 10 * YXHeightScale, width: 20 * YXHeightScale, height: 20 * YXHeightScale))
        mask2.backgroundColor = scroll.backgroundColor
        mask2.layer.cornerRadius = 10 * YXHeightScale
        scroll.addSubview(mask2)
        
        let mask3 = UIView.init(frame: CGRect.init(x: YXDeviceWidth - 20 * YXWidthScale, y: back1.bottom() - 10 * YXWidthScale, width: 20 * YXWidthScale, height: 20 * YXWidthScale))
        mask3.backgroundColor = scroll.backgroundColor
        mask3.layer.cornerRadius = 10 * YXWidthScale
        scroll.addSubview(mask3)
        
        let trayBottom = UIView.init(frame: CGRect.init(x: 0, y: YXDeviceHeight - 64 - 140 * YXHeightScale, width: YXDeviceWidth, height: 140 * YXHeightScale))
        trayBottom.backgroundColor = UIColor.white
        trayBottom.layer.borderColor = UIColor.colorWithHexString(hex: "f2f2f2").cgColor
        trayBottom.layer.borderWidth = YXHeightScale
        self.view.addSubview(trayBottom)
        let gen = UIButton.init(type: .system)
        gen.frame = CGRect.init(x: 135 * YXWidthScale, y: 16 * YXHeightScale, width: 480 * YXWidthScale, height: 108 * YXHeightScale)
        trayBottom.addSubview(gen)
        gen.backgroundColor = UIColor.black
        gen.layer.cornerRadius = YXButtonCorner
        gen.setTitle("立即结算", for: .normal)
        gen.setTitleColor(UIColor.white, for: .normal)
        gen.addTarget(self, action: #selector(estimated), for: .touchUpInside)
        trayBottom.addSubview(gen)
    }
    
    func addShopper()->Void{
        let addShoper = ShopperListViewController.init()
        addShoper.delegate = self
        self.navigationController?.pushViewController(addShoper, animated: true)
    }
    
    func deleteShop(model: ShopperModelItem) {
        if shopperModel != nil {
            if let mod = DataCacher.shared().shopper(id: String(goods_id)) {
                if mod.id == model.id{
                    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
                    let absolutePath = path + "/" + "shopper.dat"
                    do{
                        try FileManager.default.removeItem(atPath: absolutePath)
                    }catch{
                        
                    }
                }
            }
            if shopperModel!.id == model.id {
                shopperModel = nil
            }
        } else {
            if let mod = DataCacher.shared().shopper(id: String(goods_id)) {
                if mod.id == model.id{
                    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
                    let absolutePath = path + "/" + "shopper.dat"
                    do{
                        try FileManager.default.removeItem(atPath: absolutePath)
                    }catch{
                        
                    }
                }
            }
        }
    }
    
    //handleShoper delegate
    func handleShop(model: ShopperModelItem) {
        //首先根据model刷新页面,然后需要保存shoperid 
        shopperModel = model
    }
    
    func getShopper() -> Void {
        Manager.shared().getShopperList(success: {(modl) in
            if let mod = modl as? ShopperModel {
                if mod.result == true {
                    if let m = mod.shoppers.first {
                        self.shopperModel = m
                    }
                }
            }
        }, fail: {(code) in
            self.commonAlertMsg(content: YXNetWorkFail)
        })
    }
    
    @objc func estimated()->Void{
//        let content = "评估价格为" + head.priceRange + "元,是否立即结算?"
//        alertSomeMessage(title: YXAlertTitle, content: content, sureTitle: YXConfirmTitle, cancelTitle: YXCancelTitle, ensureAction: { (alert) in
//            self.uploadInfo()
//        }, cancelAction: { (alert) in
//            
//        })
        uploadInfo()
    }

    func uploadInfo() -> Void {
        
//        if shopperModel != nil {
//            finalParam["employee_id"] = String(DataCacher.shared().id())
//            finalParam["final_price"] = String(price)
//        } else {
//            commonAlertMsg(content: "手机信息不全!")
//            return
//        }
        let hall_id = DataCacher.shared().hall_id()
        let employee_id = DataCacher.shared().id()
        let param = ["id":String(id),"employee_id":String(employee_id),"final_price" : String(price),"business_hall_id" : hall_id]
        
        let finally = FinallyCaculateViewController.init()
        finally.param = param
        finally.price = NumberToString.intToFloatString(number: price, radix: 100)
        if self.model != nil {
            finally.number = self.model!.number
            finally.title = self.model!.phone_model
        }
        DataCacher.shared().fillShopper(model: self.shopperModel, id: String(self.goods_id))
        self.navigationController?.pushViewController(finally, animated: true)
    }
}
